package com.it.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.constants.FunctionConst;
import com.it.constants.SQLConst;
import com.it.domain.ResponseResult;
import com.it.domain.entity.LeaveWord;
import com.it.domain.entity.User;
import com.it.domain.vo.LeaveWordVo;
import com.it.enums.AppHttpCodeEnum;
import com.it.mapper.LeaveWordMapper;
import com.it.mapper.UserMapper;
import com.it.service.LeaveWordService;
import com.it.service.UserService;
import com.it.utils.BeanCopyUtils;
import com.it.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * (LeaveWord)表服务实现类
 *
 * @author makejava
 * @since 2024-08-15 22:53:13
 */
@Service("leaveWordService")
public class LeaveWordServiceImpl extends ServiceImpl<LeaveWordMapper, LeaveWord> implements LeaveWordService {

    @Autowired
    private LeaveWordService leaveWordService;
    @Autowired
    private LeaveWordMapper leaveWordMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult getLeaveWordList(String id) {
        List<LeaveWord> leaveWords = leaveWordService.list();
        List<LeaveWordVo> leaveWordVos = BeanCopyUtils.copyBeanList(leaveWords, LeaveWordVo.class);
        for (LeaveWordVo leaveWord : leaveWordVos) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getId, leaveWord.getUserId());
            User user = userMapper.selectOne(queryWrapper);
            leaveWord.setAvatar(user.getAvatar());
            leaveWord.setNickname(user.getNickName());
        }
        if (id != null) {
            LeaveWordVo leaveWordVo = new LeaveWordVo();
            for (LeaveWordVo leaveWord : leaveWordVos) {
                if (leaveWord.getId() == Long.valueOf(id)) {
                    leaveWordVo = leaveWord;
                }
            }
            return ResponseResult.okResult(leaveWordVo);
        }
        return ResponseResult.okResult(leaveWordVos);
    }

    @Override
    public ResponseResult userLeaveWord(String content) {
        if (content.length() > FunctionConst.LEAVE_WORD_CONTENT_LENGTH) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LEAVE_WORD_LENGTH_ERROR);
        }
        LeaveWord leaveWord = LeaveWord.builder().content(content)
                .userId(SecurityUtils.getUserId()).build();
        return this.save(leaveWord) ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.ADD_CONTENT_ERROR);
    }
}

